# -*- coding: utf-8 -*-
"""
Created---------------------------------------------------------------------------------------------
		By:
			Muhammed SHEMUNI		Developer
			Yücel KILIÇ				Developer
		at:
			Begin					01.12.2013
			Last update				06.01.2014
----------------------------------------------------------------------------------------------------
"""

import sys , os, time, string, math, signal, datetime

today = datetime.datetime.now()

os.system("echo \"-" + str(today) + "\" >>log.my")

try:
	from bwcsiiv import Ui_Form
except:
	print("bwcsiiv does not installed properly! To install\nsudo apt-get install pyqt4-dev-tools python-matplotlib")
	raise SystemExit
try:
	from PyQt4 import QtGui
	from PyQt4 import QtCore
except:
	print("pyqt4-dev-tools'? To install\nsudo apt-get install pyqt4-dev-tools")
	raise SystemExit

class MyForm(QtGui.QWidget):
  def __init__(self):
    super(MyForm, self).__init__()
    self.ui = Ui_Form()
    self.ui.setupUi(self)
    self.timer = QtCore.QBasicTimer()
    self.step = 0
    self.timer.start(15000, self)
    self.ui.checkBox_expand.clicked.connect(self.expandForm)
    
  def expandForm(self):
    if self.ui.checkBox_expand.checkState() == QtCore.Qt.Checked:
      self.resize(954, 590)
      self.ui.checkBox_expand.setGeometry(QtCore.QRect(850, 20, 87, 19))
      self.ui.checkBox_expand.setText(QtGui.QApplication.translate("Form", "Collapse", None))
    else:
      self.resize(387, 590)
      self.ui.checkBox_expand.setGeometry(QtCore.QRect(280, 20, 87, 19))
      self.ui.checkBox_expand.setText(QtGui.QApplication.translate("Form", "Expand", None))
    
  def PlotFunc(self):
    import matplotlib.pyplot as plt
    import matplotlib.dates as md
    import datetime as dt
    import time
    import dateutil
    import MySQLdb
    db = MySQLdb.connect(host="localhost", user="***", passwd="***", db="***")
    cur = db.cursor()
    # Use all the SQL you like
    limit_point = int(self.ui.comboBox.currentText())*60
    cur.execute("SELECT DAT, SKY, AMB, WIND, HUM, DEW, HEA, casee, ADAY FROM bwcsiiDAG ORDER BY dat DESC LIMIT %s" %(str(limit_point)))
    xtime = []
    humidityPercent = []
    DewPercent = []
    RainHeater = []
    CaseTemp = []
    ADAY = []
    ambientT = []
    SkyAmbientT = []
    windSpeed = []
    # print all the first cell of all the rows
    for row in cur.fetchall() :
        #Check correct date format
        if row[0][17:19] == "60":
            xtime.append(row[0][0:17] + "59")
        else:
            xtime.append(row[0][0:19])
        SkyAmbientT.append(row[1])
        ambientT.append(row[2])
        windSpeed.append(str(float(row[3])*0.277777778))
        humidityPercent.append(row[4])
        DewPercent.append(row[5])
        RainHeater.append(row[6])
        CaseTemp.append(row[7])
        ADAY.append(row[8])
    dates = [dateutil.parser.parse(s) for s in xtime]
    #self.ui.disp_chart.canvas.ax.set_ylim(-30,40)
    self.ui.disp_chart.canvas.ax.plot(dates, ambientT, "o",  color = "Red")
    #self.ui.disp_chart.canvas.ax1.set_ylim(0,200)
    self.ui.disp_chart.canvas.ax1.plot(dates, windSpeed, "o",  color = "Blue")
    #self.ui.disp_chart.canvas.ax2.set_ylim(0,100)
    self.ui.disp_chart.canvas.ax2.plot(dates, humidityPercent, "o",  color = "Green")
    self.ui.disp_chart.canvas.draw()
    db.commit()
    db.close()
  def timerEvent(self, e):
  	self.update_waather()
  	self.PlotFunc()
  
  def airsql(self, quantity):
    import MySQLdb
    db = MySQLdb.connect(host="localhost", user="***", passwd="***", db="***")
    cur = db.cursor()
    # Use all the SQL you like
    cur.execute("SELECT %s FROM bwcsiiDAG ORDER BY dat DESC LIMIT 1" %(quantity))
    # print all the first cell of all the rows
    for row in cur.fetchall() :
        result = row[0]
    return result
    db.commit()
    db.close()
    
  def update_waather(self):
    datew, timew = self.airsql("dat").split(" ")
    self.ui.label_time.setText(QtGui.QApplication.translate("Form", "<html><head/><body><p><span style=\" font-size:16pt;color:#00aa00;\">" + datew + " " + timew[0:8] + "</span></p></body></html>" , None, QtGui.QApplication.UnicodeUTF8))
    b_status, b_color = self.boltwood_CloudCond(self.airsql("C"))
    self.ui.label_sky.setText(QtGui.QApplication.translate("Form", "<html><head/><body><p><span style=\" font-size:24pt;color:" + b_color + ";\">" + b_status + "</span></p></body></html>" , None, QtGui.QApplication.UnicodeUTF8))
    b_status, b_color = self.boltwood_WindCond(self.airsql("W"))
    self.ui.label_wind.setText(QtGui.QApplication.translate("Form", "<html><head/><body><p><span style=\" font-size:24pt;color:" + b_color + ";\">" + b_status + "</span></p></body></html>" , None, QtGui.QApplication.UnicodeUTF8))
    b_status, b_color = self.boltwood_RainCond(self.airsql("R"))    
    self.ui.label_rain.setText(QtGui.QApplication.translate("Form", "<html><head/><body><p><span style=\" font-size:24pt;color:" + b_color + ";\">" + b_status + "</span></p></body></html>" , None, QtGui.QApplication.UnicodeUTF8))
    b_status, b_color = self.boltwood_DayCond(self.airsql("D2"))      
    self.ui.label_light.setText(QtGui.QApplication.translate("Form", "<html><head/><body><p><span style=\" font-size:24pt;color:" + b_color + ";\">" + b_status + "</span></p></body></html>" , None, QtGui.QApplication.UnicodeUTF8))
    self.ui.lcdNumber_atemp.display(format(float(self.airsql("AMB")), '.1f'))
    self.ui.lcdNumber_wind.display(format(float(self.airsql("WIND"))*0.277777778, '.1f'))
    self.ui.lcdNumber_humidity.display(format(float(self.airsql("HUM")), '.1f'))
    self.ui.lcdNumber_stemp.display(format(float(self.airsql("SKY")), '.1f'))
    self.ui.lcdNumber_sentemp.display(format(float(self.airsql("casee")), '.1f'))
    self.ui.lcdNumber_devp.display(format(float(self.airsql("DEW")), '.1f'))
    self.ui.lcdNumber_rheater.display(format(float(self.airsql("HEA")), '.1f'))
    self.ui.lcdNumber_daylight.display(format(float(self.airsql("ADAY")[0:4]), '.1f'))
    
  def boltwood_SkyCond(self, bw_status):
    #skyCond
    if bw_status == "0":
      dp_status = "Sky is Unknown"
      dp_color = "black"      
    elif bw_status == "1":
      dp_status = "Clear"
      dp_color = "green"
    elif bw_status == "2":
      dp_status = "Cloudy"
      dp_color = "orange"
    elif bw_status == "3":
      dp_status = "Very Cloudy"
      dp_color = "red"
    elif bw_status == "4":
      dp_status = "Wet"
      dp_color = "blue"
    elif bw_status == "skyNA":
      dp_status = "N/A"
      dp_color = "red"
    return dp_status, dp_color     
  
  def boltwood_CloudCond(self, bw_status):
    #CloudCond
    if bw_status == "0":
      dp_status = "Cloud is Unknown"
      dp_color = "black"      
    elif bw_status == "1":
      dp_status = "Clear"
      dp_color = "green"
    elif bw_status == "2":
      dp_status = "Cloudy"
      dp_color = "orange"
    elif bw_status == "3":
      dp_status = "Very Cloudy"
      dp_color = "red"
    elif bw_status == "CloudNA":
      dp_status = "N/A"
      dp_color = "red"
    return dp_status, dp_color 

  def boltwood_WetCond(self, bw_status):
    #WetFlag
    if bw_status == "0":
      dp_status = "Dry"
      dp_color = "green"
    elif bw_status == "1":
      dp_status = "Wet"
      dp_color = "red"
    return dp_status, dp_color
    
  def boltwood_WindCond(self, bw_status):
    #windCond    
    if bw_status == "0":
      dp_status = "Wind Unknown"
      dp_color = "black"      
    elif bw_status == "1":
      dp_status = "Calm"
      dp_color = "green"
    elif bw_status == "2":
      dp_status = "Windy"
      dp_color = "orange"
    elif bw_status == "3":
      dp_status = "Very Windy"
      dp_color = "red"
    elif bw_status == "windNA":
      dp_status = "N/A"
      dp_color = "red"
    return dp_status, dp_color
    
  def boltwood_RainCond(self, bw_status):
    #rainCond    
    if bw_status == "0":
      dp_status = "Unknown"
      dp_color = "black"      
    elif bw_status == "1":
      dp_status = "Dry"
      dp_color = "green"
    elif bw_status == "2":
      dp_status = "Recent"
      dp_color = "orange"
    elif bw_status == "3":
      dp_status = "Rainning"
      dp_color = "red"
    elif bw_status == "rainNA":
      dp_status = "N/A"
      dp_color = "red"
    return dp_status, dp_color
    
  def boltwood_DayCond(self, bw_status):
    #dayCond    
    if bw_status == "1":
      dp_status = "Dark"
      dp_color = "green"
    elif bw_status == "2":
      dp_status = "Light"
      dp_color = "orange"
    elif bw_status == "3":
      dp_status = "Very Light"
      dp_color = "red"
    elif bw_status == "dayNA":
      dp_status = "N/A"
      dp_color = "red"
    elif bw_status == "0":
      dp_status = "Unknown"
      dp_color = "black"  
    return dp_status, dp_color

app = QtGui.QApplication(sys.argv)
f = MyForm()
f.show()
app.exec_()
